package com.jms.fu.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;





import com.jms.fu.common.UIMessage;
import com.jms.fu.exception.DAOException;
import com.jms.fu.form.ChangePasswordForm;
import com.jms.fu.model.bo.UserBO;
import com.jms.fu.vaidator.TextFieldValidator;

public class ChangePasswordAction extends Action {
	private static Logger logger = Logger.getLogger(LoginAction.class);

	/**
	 * Method execute, called when executing the action
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		ChangePasswordForm changePasswordForm = (ChangePasswordForm) form;
		UserBO userBO = new UserBO();
		HttpSession session = request.getSession();
		String oldPassword = changePasswordForm.getOldPassword();
		String newPassword = changePasswordForm.getNewPassword();
		String username =(String) session.getAttribute("username");
		TextFieldValidator txtValid = new TextFieldValidator();
		try {
			if (!txtValid.validate(newPassword)) {
				request.setAttribute("info", "Your new password is too short" );
				return mapping.findForward("failed");
			}
			if (userBO.checkPassword(username,oldPassword)) {
				request.setAttribute("info", UIMessage.INVALID_OLD_PASSWORD );
				return mapping.findForward("failed");
			}
			userBO.changePassword(username,newPassword);
			request.setAttribute("info", UIMessage.CHANGE_PASSWORD_SUCCESS );
			return mapping.findForward("success");
		} catch (DAOException e) {
			logger.error(e.getMessage());
			return mapping.findForward("error");
		}
		
	}
}
